import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) throws IOException {
        int answer;
        //while (true) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        try {
            serverForClient = new ServerSocket(2019);
        } catch (IOException e1) {
            System.out.println(e1);
        }
        try {
            System.out.println("等待客户呼叫");
            socketOnServer = serverForClient.accept(); //堵塞状态，除非有客户呼叫
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            String s = in.readUTF(); // in读取信息，堵塞状态

            // 获取密文
            FileInputStream f=new FileInputStream("SEnc.dat");
            int num=f.available();
            byte[ ] ctext=new byte[num];
            f.read(ctext);
            // 获取密钥
            FileInputStream  f2=new FileInputStream("keykb1.dat");
            int num2=f2.available();
            byte[ ] keykb=new byte[num2];
            f2.read(keykb);
            SecretKeySpec k=new  SecretKeySpec(keykb,"DESede");
            // 解密
            Cipher cp=Cipher.getInstance("DESede");
            cp.init(Cipher.DECRYPT_MODE, k);
            byte []ptext=cp.doFinal(ctext);
            // 显示明文
            String p=new String(ptext,"UTF8");

            System.out.println("服务器收到客户的提问:" + p);
            MyDC myDC = new MyDC();
            answer = myDC.evaluate(p);
            out.writeUTF(answer + "");
            Thread.sleep(500);
        } catch (Exception e) {
            System.out.println("客户已断开" + e);
        }
        //}
    }
}
